//
//  BBOutAnimation.swift
//  BBAnimatedTransitioning
//
//  Created by YouMao on 2022/4/29.
//

import Foundation

/// 退出动画
public enum BBOutAnimation {
    case `default`
    case view(_ view:UIView, to:CGRect)
}

// MARK: - Animation Methods
extension BBOutAnimation {
    
    /// 默认动画效果
    func defaultAnimation(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval) {
        let containerView = transitionContext.containerView
        if let toView = transitionContext.view(forKey: .to) {
            containerView.addSubview(toView)
        }
        guard let fromeView = transitionContext.view(forKey: .from) else { return }
        containerView.addSubview(fromeView)
        UIView.animate(withDuration: duration, delay: 0, options: []) {
            fromeView.frame = CGRect(x: containerView.bounds.size.width, y: fromeView.frame.origin.y, width: fromeView.frame.size.width, height: fromeView.frame.size.height)
        } completion: { finished in
            if finished {
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        }
    }
    
    /// 某个view移动效果
    func viewToFrameAnimation(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval, view:UIView, to:CGRect) {
        let containerView = transitionContext.containerView
        if let toView = transitionContext.view(forKey: .to) {
            containerView.addSubview(toView)
        }

        guard let fromeView = transitionContext.view(forKey: .from) else { return }
        containerView.addSubview(fromeView)
        
        UIView.animate(withDuration: duration, delay: 0, options: []) {            fromeView.backgroundColor = .clear
            view.frame = to
        } completion: { finished in
            if finished {
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        }
    }
}

// MARK: - BBTransitiontingAnimatorDelegate
extension BBOutAnimation: BBTransitiontingAnimatorDelegate {
    
    public func implement(_ transitionContext: UIViewControllerContextTransitioning, duration: TimeInterval) {
        switch self {
        case .view(let view, to: let frame):
            viewToFrameAnimation(transitionContext, duration: duration, view: view, to: frame)
        case .default:
            defaultAnimation(transitionContext, duration: duration)
        }
    }
}
